package com.bw.zg3_day05zy.news

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.IntRange
import androidx.databinding.DataBindingUtil
import androidx.paging.PagingDataAdapter
import androidx.recyclerview.widget.DiffUtil.ItemCallback
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.bw.base.entity.NewsBeanItem
import com.bw.zg3_day05zy.R
import com.bw.zg3_day05zy.databinding.ItemNewsBinding


class NewsAdapter: PagingDataAdapter<NewsBeanItem, NewsAdapter.NewsViewHolder>(diff) {
    private var mOnItemClickListener: OnItemClickListener? = null
    companion object{
        val diff = object : ItemCallback<NewsBeanItem>(){
            override fun areItemsTheSame(oldItem: NewsBeanItem, newItem: NewsBeanItem): Boolean {
                return oldItem == newItem
            }

            override fun areContentsTheSame(oldItem: NewsBeanItem, newItem: NewsBeanItem): Boolean {
                return oldItem.id == newItem.id
            }
        }
    }
    class NewsViewHolder(view: View):ViewHolder(view) {
        val binding = DataBindingUtil.bind<ItemNewsBinding>(view)
    }

    override fun onBindViewHolder(holder: NewsViewHolder, position: Int) {
        val item = getItem(position)
        holder.binding?.bean = item
        holder.itemView.setOnClickListener {
            this.mOnItemClickListener?.onItemClick(item!!,position)
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NewsViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_news, parent, false)
        return NewsViewHolder(view)
    }

    //点击事件
    fun setOnItemClickListener(listener: OnItemClickListener?) {
        this.mOnItemClickListener = listener
    }

    interface OnItemClickListener {
        fun onItemClick(item: NewsBeanItem, position: Int)
    }

}